import biwMetaService from '@services/biwmeta';
import { Toast } from 'react-vant'

// 定义常量
const $WALLET_PLAOC_PATH = {
  getAddress: '/wallet/authorize/address',
  signature: '/wallet/authorize/signature',
};

const CHAIN_NAME = {
  BIWMeta: 'BIWMeta',
  Binance: 'Binance',
  Tron: 'Tron',
  Ethereum: 'Ethereum',
  Bitcoin: 'Bitcoin',
};

const $WALLET_AUTHORIZE_ADDRESS_TYPE = {
  main: 'main',
  network: 'network',
  all: 'all',
};

const $WALLET_SIGNATURE_TYPE = {
  message: 'message',
  transfer: 'transfer',
  bioforestChainCertificateTransfer: 'bioforestChainCertificateTransfer',
  json: 'json',
  ENTITY: 'ENTITY',
  assetTypeBalance: 'assetTypeBalance',
  contract: 'contract',
};

// 定义类型（JavaScript 中无需显式定义类型，但可以保留注释以便理解）
/**
 * 地址返回类型
 * @typedef {Object} $WEALLET_ADDRESS_RESPONSE
 * @property {string} name - 钱包名称
 * @property {string} chainName - 链名称
 * @property {string} address - 地址
 * @property {string} publicKey - 公钥
 * @property {string} magic - BIW链的magic标识符
 * @property {string} [signMessage] - 签名消息（如果有）
 */

/**
 * 获取地址对应币种余额类型
 * @typedef {Object} $WALLET_ASSETTYPE_BALANCE
 * @property {string} type - 签名类型
 * @property {string} chainName - 链名称
 * @property {string} senderAddress - 发送地址
 * @property {Array<{assetType: string, contractAddress?: string}>} assetTypes - 币种列表
 */

/**
 * 签名返回类型
 * @typedef {Object} $WEALLET_SIGNATURE_RESPONSE
 * @property {string} [assetType] - 币种
 * @property {number} [decimals] - 精度
 * @property {string} [balance] - 余额
 * @property {string} [contracts] - 合约
 */

class BiwMeta {
  constructor(props) {
    const { sign } = props || {};
    this.signText = sign || 'login';
    this.signList = [];
  }

  getSign() {
    return this.signList;
  }

  async getBalance() {
    const address = this.signList;
    if (!address) {
      alert("未登录地址");
      return;
    }
    // 检查是否安装了应用
    const hasId = await biwMetaService.canOpenId(import.meta.env.VITE_BIW_META_ID);
    if (!hasId) {
      alert(`未安装BIW Meta(${import.meta.env.VITE_BIW_META_ID})`);
      return;
    }
    console.log(this.signList);
    const res = await biwMetaService.getBIWMetaAppData(
      import.meta.env.VITE_BIW_META_ID,
      $WALLET_PLAOC_PATH.signature,
      [{
        type: $WALLET_SIGNATURE_TYPE.assetTypeBalance,
        chainName: this.signContent.chainName,
        senderAddress: this.signContent.address,
        assetTypes: [{
          assetType: 'BIW', // 币种
        }],
      }]
    );
    const data = await res.getData();
    // 得到数据，聚焦本窗口
    await biwMetaService.focusWindow();
    if (data) {
      const res = data[0];
      if (res) {
        const assetTypeInfo = (data[0] || {})['BIW'];
        return assetTypeInfo?.balance || '0';
      } else {
        return '0';
      }
    }
    console.log("授权失败");
  }

  async sign() {
    try {
      const hasId = await biwMetaService.canOpenId(import.meta.env.VITE_BIW_META_ID);
      if (!hasId) {
        alert(`未安装BIW Meta(${import.meta.env.VITE_BIW_META_ID})`);
        return;
      }
      const res = await biwMetaService.getBIWMetaAppData(
        import.meta.env.VITE_BIW_META_ID,
        $WALLET_PLAOC_PATH.getAddress,
        {
          type: $WALLET_AUTHORIZE_ADDRESS_TYPE.main,
          chainName: CHAIN_NAME.BIWMeta,
          signMessage: this.signText,
        }
      );
      const data = await res.getData();
      // 得到数据，聚焦本窗口
      await biwMetaService.focusWindow();
      if (data) {
        this.signList = data;
        return data;
      }
      Toast.info('签名失败');
      throw '签名失败'; // 抛出错误信息
    } catch (error) {
      Toast.info('签名失败'); // 显示失败的提示信息
      throw '签名失败'; // 抛出错误信息
    }
  }
}

export default BiwMeta;